import { reactive, toRefs } from "vue"
import { onShow, onReady, onUnload, onLoad } from "@dcloudio/uni-app";
import { LoginStore } from "@/store/modules/login";
import config from "@/config/config";
const uniIdCo = uniCloud.importObject("uni-id-co", { customUI: true })
/**
 * @description  昵称+密码+验证码注册逻辑
 * @param formRefs 表单校验实例
 * @param rules 表单校验规则
 * @param 
 * */
export const useRegister = (formRefs, rules, captchaRef, agreementsRef, captcha = false) => {
    const state = reactive({
        formData: {
            username: '', //账号
            password: '', //密码
            mobile: '', //手机号
            captcha: '', //图形验证码
            inviteCode: '' //邀请码
        },
        formItem: {
            loading: false, //防抖
            eyeShow: false, //密码显示状态
            tips: "", //按钮提示文本
            disabled: false //禁用状态
        },
        uniIdRedirectUrl: '', //注册前所在的页面地址
        // 校验规则
        rules
    });

    onLoad((e) => {
        if (e.uniIdRedirectUrl) {
            state.uniIdRedirectUrl = decodeURIComponent(e.uniIdRedirectUrl)
        }
        // #ifdef MP-WEIXIN
        if (getCurrentPages().length === 1) {
            uni.hideHomeButton()
            console.log('已隐藏：返回首页按钮');
        }
        // #endif
    })
    onReady(() => {
        // 兼容小程序的校验 (uview中使用)
		if(formRefs.value.setRules)  formRefs.value.setRules(state.rules)
    });

    // 兼容H5
    onShow(() => {
        // #ifdef H5
        document.onkeydown = event => {
            var e = event || window.event;
            if (e && e.keyCode == 13) { //回车键的键值为13
                submit()
            }
        };
        // #endif
    })

    // 卸载键盘事件
    onUnload(() => {
        // #ifdef H5
        document.onkeydown = false
        // #endif
    });
    /**
     * @description: 注册事件
     * @param {*} formRef 表单实例
     * @param {*} captchaRef 验证码实例
     * @param {*} agreementsRef 隐私协议实例
     */
    const submit = async () => {
		formRefs.value.validator().then(res => {
            //  如果没有输入验证码就提示输入验证码
            if (state.formData.captcha.length != 4 && captcha) {
                // 让验证码输入框获取焦点
                if (captchaRef) captchaRef.focusCaptchaInput = true
                return uni.showToast({
                    title: '请输入验证码',
                    icon: 'none',
                    duration: 3000
                });
            }
            // 校验用户协议是否勾选，如果没有把提交事件传递过去，用于候选后自动注册
            if (agreementsRef.needAgreements.value && !agreementsRef.isAgree.value) {
                return agreementsRef.popup(() => submitForm(captchaRef))
            }
			if(!res.isPassed) return
            // 如果校验通过直接提交注册
            submitForm(captchaRef)
        }).catch((errors) => {
            console.log(errors);
        })
    }

    /**
     * @description: 注册接口
     * @param {*} captchaRef 验证码实例
     */
    const submitForm = async (captchaRef) => {
        try {
            let res;
            if (!config.isAdmin) {
                res = await uniIdCo.registerUser(state.formData)
            } else {
                res = await uniIdCo.registerAdmin(state.formData)
            }
            // 用于注册成功时需要配置的逻辑（如存储信息，记录设备，记录登录日志）
            const LoginState = LoginStore()
            if (!config.isAdmin) LoginState.loginSuccess({ ...res, toastText: '注册成功',uniIdRedirectUrl: state.uniIdRedirectUrl })
            // 注册成功后返回登录页面
            toLoing()
        } catch (e) {
            console.log(e.errCode);
            console.log(e.errMsg);
            //更好的体验：登录错误，直接刷新验证码
            captchaRef.getImageCaptcha()
            // 只有当是admin的时候才给与提示
            uni.showModal({
                title: '提示',
                content: e.errMsg || `创建失败: ${e.errCode}`,
                showCancel: false
            })

        }
    }

    // 去登录
    const toLoing = () => {
        uni.navigateBack()
    }
    return {
        ...toRefs(state),
        submit,
        toLoing
    };
};